// 页面元素
const welcomePage = document.getElementById('welcome-page');
const loadingPage = document.getElementById('loading-page');
const resultPage = document.getElementById('result-page');
const userInput = document.getElementById('user-input');
const voiceBtn = document.getElementById('voice-btn');
const submitBtn = document.getElementById('submit-btn');
const loadingText = document.getElementById('loading-text');
const dessertName = document.getElementById('dessert-name');
const dessertStory = document.getElementById('dessert-story');
const ingredientsList = document.getElementById('ingredients-list');
const instructions = document.getElementById('instructions');
const remixBtn = document.getElementById('remix-btn');
const saveBtn = document.getElementById('save-btn');

// 加载页面的引导语文本
const loadingTexts = [
    "通义灵码 AI 甜品师正为你精心构思",
    "正在挑选最合适的食材",
    "正在为你的甜品注入甜蜜魔法",
    "马上就要完成创作",
    "正在为你的甜品编写美味故事",
    "正在寻找最诱人的摆盘灵感",
    "正在为你的甜品故事选配照片"
];

// 甜品数据示例
const dessertData = [
    {
        name: "夏日芒果椰香慕斯",
        story: "这款慕斯的灵感来源于热带海滩的悠闲时光。芒果的浓郁甜香象征着夏日阳光，椰奶的清香如同海风轻拂。每一口都仿佛在品尝夏日的甜蜜回忆，让人忘却烦恼，沉浸在美好的假期氛围中。",
        ingredients: [
            "芒果 2个（约300g果肉）",
            "椰浆 100ml",
            "淡奶油 200ml",
            "吉利丁片 10g",
            "细砂糖 30g"
        ],
        instructions: "1. 吉利丁片冷水泡软备用\n2. 芒果打成泥，加热至微沸后加入泡软的吉利丁片\n3. 椰浆和淡奶油混合打发至六分发\n4. 将芒果泥与打发的椰浆奶油混合均匀\n5. 倒入模具冷藏4小时以上至凝固"
    },
    {
        name: "焦糖海盐巧克力塔",
        story: "灵感来源于一次海边日落，咸味代表海风，甜味象征夕阳，微苦的巧克力是夜幕降临前的温柔告别。这是一款充满诗意的甜品，每一口都诉说着浪漫的故事。",
        ingredients: [
            "黑巧克力 150g",
            "黄油 80g",
            "鸡蛋 2个",
            "细砂糖 60g",
            "海盐 2g",
            "塔皮 1个"
        ],
        instructions: "1. 巧克力和黄油隔水融化\n2. 鸡蛋和糖打发至浓稠\n3. 将巧克力液倒入蛋糊中拌匀\n4. 加入海盐拌匀\n5. 倒入塔皮中，烤箱180度烤制20分钟"
    },
    {
        name: "清新柠檬蛋白霜",
        story: "这款甜品如同春日清晨的第一缕阳光，清新的柠檬香气能够瞬间唤醒你的味蕾。轻盈的蛋白霜如云朵般柔软，带来无负担的甜蜜享受。",
        ingredients: [
            "柠檬 3个",
            "蛋白 4个",
            "细砂糖 120g",
            "玉米淀粉 10g",
            "蓝莓 适量（装饰用）"
        ],
        instructions: "1. 柠檬榨汁，取皮屑备用\n2. 蛋白打发至粗泡，分次加入糖\n3. 继续打发至湿性发泡\n4. 加入柠檬汁和皮屑拌匀\n5. 裱花袋挤出造型，烤箱150度烤制40分钟"
    },
    {
        name: "樱花草莓芝士蛋糕",
        story: "春天的浪漫在这款蛋糕中绽放。粉色的外表如樱花般娇嫩，草莓的酸甜搭配芝士的浓郁，仿佛在品尝整个春天的温柔。",
        ingredients: [
            "奶油奶酪 250g",
            "淡奶油 100ml",
            "消化饼干 100g",
            "黄油 50g",
            "草莓 200g",
            "樱花蜜饯 适量"
        ],
        instructions: "1. 饼干压碎与融化的黄油混合，铺在模具底部\n2. 奶油奶酪室温软化后打顺\n3. 加入淡奶油继续打发\n4. 草莓切片加入奶酪糊中拌匀\n5. 倒入模具，表面装饰樱花蜜饯，冷藏4小时"
    },
    {
        name: "秋日栗子蒙布朗",
        story: "秋日的暖阳洒在山林间，满树的栗子散发着诱人的香气。这款蒙布朗将栗子的香甜发挥到极致，每一口都是秋天的味道。",
        ingredients: [
            "栗子仁 300g",
            "淡奶油 200ml",
            "蛋白 2个",
            "细砂糖 80g",
            "朗姆酒 10ml"
        ],
        instructions: "1. 栗子仁煮熟后压成泥\n2. 加入朗姆酒拌匀备用\n3. 蛋白打发至粗泡，分次加糖打发\n4. 淡奶油打发至六分发\n5. 将栗子泥与蛋白霜、奶油混合\n6. 裱花袋挤出造型装饰"
    }
];

// 检查输入是否完整以显示提交按钮
function checkInput() {
    if (userInput.value.trim().length > 0) {
        submitBtn.classList.remove('hidden');
    } else {
        submitBtn.classList.add('hidden');
    }
}

// 语音输入模拟
function startVoiceInput() {
    // 检查是否支持语音识别
    if ('webkitSpeechRecognition' in window) {
        const recognition = new webkitSpeechRecognition();
        recognition.lang = 'zh-CN';
        recognition.continuous = false;
        recognition.interimResults = false;
        
        recognition.onstart = function() {
            voiceBtn.innerHTML = '<i class="fas fa-spinner fa-spin text-2xl"></i>';
            voiceBtn.classList.add('animate-pulse');
        };
        
        recognition.onresult = function(event) {
            const transcript = event.results[0][0].transcript;
            userInput.value = transcript;
            voiceBtn.classList.remove('animate-pulse');
            voiceBtn.innerHTML = '<i class="fas fa-microphone text-2xl"></i>';
            checkInput();
        };
        
        recognition.onerror = function(event) {
            console.error('语音识别出错:', event.error);
            voiceBtn.classList.remove('animate-pulse');
            voiceBtn.innerHTML = '<i class="fas fa-microphone text-2xl"></i>';
            // 使用示例文本作为备选
            startVoiceInputFallback();
        };
        
        recognition.start();
    } else {
        // 不支持语音识别时使用模拟
        startVoiceInputFallback();
    }
}

// 语音输入备选方案
function startVoiceInputFallback() {
    voiceBtn.innerHTML = '<i class="fas fa-spinner fa-spin text-2xl"></i>';
    voiceBtn.classList.add('animate-pulse');
    
    // 模拟语音识别结果
    setTimeout(() => {
        const sampleInputs = [
            "我想要一个适合夏天的、低糖的芒果慕斯",
            "有没有适合下午茶的、不甜的柠檬蛋糕？",
            "请为我设计一个情人节的浪漫甜品",
            "我想要一个无麸质的巧克力甜品",
            "有没有适合秋天的栗子甜品？",
            "我想做一个生日蛋糕，要粉色的",
            "有没有不含乳制品的甜品推荐？"
        ];
        
        userInput.value = sampleInputs[Math.floor(Math.random() * sampleInputs.length)];
        voiceBtn.classList.remove('animate-pulse');
        voiceBtn.innerHTML = '<i class="fas fa-microphone text-2xl"></i>';
        checkInput();
    }, 2000);
}

// 显示加载页面
function showLoadingPage() {
    welcomePage.classList.add('hidden');
    loadingPage.classList.remove('hidden');
    
    // 轮播加载文本
    let textIndex = 0;
    const textInterval = setInterval(() => {
        loadingText.textContent = loadingTexts[textIndex];
        textIndex = (textIndex + 1) % loadingTexts.length;
    }, 2000);
    
    // 模拟加载过程
    setTimeout(() => {
        clearInterval(textInterval);
        showResultPage();
    }, 15000);
}

// 显示结果页面
function showResultPage() {
    // 根据用户输入关键词选择合适的甜品
    let selectedDessert = dessertData[Math.floor(Math.random() * dessertData.length)];
    const userText = userInput.value.toLowerCase();
    
    // 根据用户输入关键词匹配甜品
    if (userText.includes("夏天") || userText.includes("夏日") || userText.includes("芒果")) {
        selectedDessert = dessertData[0]; // 夏日芒果椰香慕斯
    } else if (userText.includes("巧克力")) {
        selectedDessert = dessertData[1]; // 焦糖海盐巧克力塔
    } else if (userText.includes("柠檬")) {
        selectedDessert = dessertData[2]; // 清新柠檬蛋白霜
    } else if (userText.includes("春天") || userText.includes("樱花") || userText.includes("草莓")) {
        selectedDessert = dessertData[3]; // 樱花草莓芝士蛋糕
    } else if (userText.includes("秋天") || userText.includes("栗子")) {
        selectedDessert = dessertData[4]; // 秋日栗子蒙布朗
    }
    
    // 填充甜品信息
    dessertName.textContent = selectedDessert.name;
    dessertStory.textContent = selectedDessert.story;
    
    // 填充食材清单
    ingredientsList.innerHTML = '';
    selectedDessert.ingredients.forEach(ingredient => {
        const li = document.createElement('li');
        li.textContent = ingredient;
        li.className = 'ingredient-item text-gray-600';
        ingredientsList.appendChild(li);
    });
    
    // 填充制作要点
    instructions.innerHTML = selectedDessert.instructions.replace(/\n/g, '<br>');
    
    loadingPage.classList.add('hidden');
    resultPage.classList.remove('hidden');
    
    // 添加卡片动画效果
    setTimeout(() => {
        document.getElementById('result-card').classList.add('translate-y-0');
    }, 100);
}

// 重新开始
function remix() {
    resultPage.classList.add('hidden');
    welcomePage.classList.remove('hidden');
    userInput.value = '';
    voiceBtn.innerHTML = '<i class="fas fa-microphone text-2xl"></i>';
    voiceBtn.classList.remove('hidden');
    submitBtn.classList.add('hidden');
}

// 保存配方
function saveRecipe() {
    // 创建要保存的内容
    const recipeContent = `
甜品名称: ${dessertName.textContent}

背后故事: ${dessertStory.textContent}

食材清单:
${Array.from(ingredientsList.children).map(li => li.textContent).join('\n')}

制作要点:
${instructions.textContent}
    `.trim();
    
    // 创建Blob对象并下载
    const blob = new Blob([recipeContent], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${dessertName.textContent}_配方.txt`;
    document.body.appendChild(a);
    a.click();
    
    // 清理
    setTimeout(() => {
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        alert('配方已保存到您的设备！');
    }, 0);
}

// 事件监听器
userInput.addEventListener('input', checkInput);
voiceBtn.addEventListener('click', startVoiceInput);
submitBtn.addEventListener('click', showLoadingPage);
remixBtn.addEventListener('click', remix);
saveBtn.addEventListener('click', saveRecipe);

// 初始化检查
checkInput();

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
    @keyframes marquee1 {
        0% { transform: translateX(100%); }
        100% { transform: translateX(-100%); }
    }
    
    @keyframes marquee2 {
        0% { transform: translateX(-100%); }
        100% { transform: translateX(100%); }
    }
    
    @keyframes progress {
        0% { width: 0%; }
        100% { width: 100%; }
    }
    
    .animate-marquee1 {
        animation: marquee1 20s linear infinite;
    }
    
    .animate-marquee2 {
        animation: marquee2 20s linear infinite;
    }
    
    .animate-progress {
        animation: progress 15s linear;
    }
    
    #result-card {
        opacity: 0;
        transform: translateY(20px);
        transition: all 0.5s ease-out;
    }
    
    #result-card.translate-y-0 {
        opacity: 1;
        transform: translateY(0);
    }
    
    .ingredient-item {
        animation: fadeIn 0.5s ease-out forwards;
    }
    
    @keyframes fadeIn {
        0% { opacity: 0; transform: translateY(10px); }
        100% { opacity: 1; transform: translateY(0); }
    }
`;
document.head.appendChild(style);